package de.encryptor.types;

import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.hibernate.type.BigDecimalType;
import org.jasypt.encryption.pbe.StandardPBEBigDecimalEncryptor;
import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

public class EncryptedBigDecimal extends BigDecimalType {
	private static final long serialVersionUID = 1L;
	private static StandardPBEBigDecimalEncryptor encryptor;
	private static def encryptorConfig = CH.config.encryptor
	
	@Override
	public Object get(ResultSet rs, String name) throws SQLException {
		return getEncryptor().decrypt(super.get(rs, name))?.floatValue();
	}
	
	@Override
	public void set(PreparedStatement st, Object value, int index) throws SQLException {
		if (value == null) {
			super.set(st, value, index);
		} else {
			super.set(st, getEncryptor().encrypt(value), index);
		}
	}
	
	public static StandardPBEBigDecimalEncryptor getEncryptor() {
		if (encryptor == null) {
			encryptor = new StandardPBEBigDecimalEncryptor();
			encryptor.algorithm=encryptorConfig.algorithm?encryptorConfig.algorithm:"PBEWithMD5AndTripleDES"
			encryptor.password=encryptorConfig.password?encryptorConfig.password:"jasypt"
			encryptor.keyObtentionIterations=encryptorConfig.keyObtentionIterations?encryptorConfig.keyObtentionIterations:1000
		}
		return encryptor
	}
}
